package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.data.transfer.service.MkSiteBasicService;
import com.caocaog.market.entity.Member;
import com.caocaog.market.mapper.MemberMapper;
import com.caocaog.market.service.MemberService;
import com.caocaog.market.vo.MemberLoginSuccessVO;
import com.caocaog.market.vo.MemberVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 会员信息
 *
 * @author chechen
 * @date 2021-11-19
 */
@Service
@Slf4j
@Transactional
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    // 会员用户名前缀
    @Value("${member.username.prefix}")
    private String memberUsernamePrefix;
    @Autowired
    private MkSiteBasicService mkSiteBasicService;
//    @Autowired
//    private RedisUtil redisUtil;

    @Override
    public Result login(Member member) {
        //验证微信用户
        //get openid
        if (oConvertUtils.isNotEmpty(member.getWxOpenid())) {
            Member memberOld = super.baseMapper.selectOne(new QueryWrapper<Member>().eq("wx_openid", member.getWxOpenid()).last(" limit 1 "));
            if (null != memberOld) {

                boolean flag = false;
//               Object uniodnid =  redisUtil.get(member.getWxOpenid());
                if (oConvertUtils.isNotEmpty(member.getMobile())) {
                    memberOld.setMobile(member.getMobile());
                    flag = true;
                }

                if (oConvertUtils.isNotEmpty(member.getNickName())) {
                    memberOld.setNickName(member.getNickName());
                    flag = true;
                }

                if (oConvertUtils.isNotEmpty(member.getAvatar())) {
                    memberOld.setAvatar(member.getAvatar());
                    flag = true;
                }
                if (flag) {
                    super.baseMapper.updateById(memberOld);
                }

                String appSign = JwtUtil.appSign(memberOld.getId());
                return Result.OK(new MemberLoginSuccessVO(appSign, memberOld));
            } else {
                if (oConvertUtils.isNotEmpty(member.getMobile())) {
                    //check
                    Member checkMobile = super.baseMapper.selectOne(new QueryWrapper<Member>()
                            .eq("mobile", member.getMobile())
                            .eq("status", 0)
                            .last(" limit 1 "));
                    if (oConvertUtils.isEmpty(checkMobile)) {
                        member.setLoginName(member.getMobile());//默认手机号
                    } else {
                        //存在手机号
                        return Result.error("手机号已存在~");
                    }
                }

                //新增
                member.setSource(MarketConstant.SOURCE_WX_MINI);
                String userId = IdWorker.getIdStr(member);
                String defaultUserName = memberUsernamePrefix + "SDX" + userId;
                member.setId(String.valueOf(IdWorker.getId()));
                member.setUserName(defaultUserName);
                member.setCreateTime(new Date());
                member.setCreateBy(defaultUserName);
                member.setDelFlag(CommonConstant.DEL_FLAG_0);
                // 处理密码
                String salt = oConvertUtils.randomGen(8);
                member.setSalt(salt);
                String b;
                if (StringUtils.isBlank(member.getMobile())) {
                    b = "0000";
                } else {
                    b = member.getMobile().substring(member.getMobile().length() - 7);
                }
                member.setUserPwd(PasswordUtil.encrypt(member.getUserName(), b, salt));
                member.setLockVersion(1);
                member.setStatus(0);
                //设置分站
                String siteId = mkSiteBasicService.getSurroundingSiteId(member.getRegistLat(), member.getRegistLng()).getSiteId();
                log.info("-----设置分站id:" + siteId);
                member.setSiteId(siteId);
                super.baseMapper.insert(member);
                String appSign = JwtUtil.appSign(member.getId());
                return Result.OK(new MemberLoginSuccessVO(appSign, member));
            }
        } else {
            return Result.error("操作失败，缺少参数~");
        }
    }

    @Override
    public Result syncSDXMember(Member member) {
        if (oConvertUtils.isNotEmpty(member.getMobile())) {
            //check
            Member checkMobile = super.baseMapper.selectOne(new QueryWrapper<Member>()
                    .eq("mobile", member.getMobile())
                    .eq("status", 0)
                    .last(" limit 1 "));

            if (oConvertUtils.isEmpty(checkMobile)) {
                member.setLoginName(member.getMobile());//默认手机号
            } else {
                if (oConvertUtils.isEmpty(checkMobile.getWxUnionid())) {
                    checkMobile.setWxUnionid(member.getWxUnionid());
                    super.baseMapper.updateById(checkMobile);
                    //存在手机号
                    String appSign = JwtUtil.appSign(checkMobile.getId());
                    return Result.OK(new MemberLoginSuccessVO(appSign, checkMobile));
                } else {
                    //存在手机号
                    String appSign = JwtUtil.appSign(checkMobile.getId());
                    return Result.OK(new MemberLoginSuccessVO(appSign, checkMobile));
                }

            }
        }

        member.setId(String.valueOf(IdWorker.getId()));
        //新增
        member.setSource(MarketConstant.SOURCE_WX_MINI_4);//送大侠小程序
        String userId = IdWorker.getIdStr(member);
        String defaultUserName = memberUsernamePrefix + userId;

        member.setUserName(defaultUserName);
        member.setCreateTime(new Date());
        member.setCreateBy(defaultUserName);
        member.setDelFlag(CommonConstant.DEL_FLAG_0);
        // 处理密码
        String salt = oConvertUtils.randomGen(8);
        member.setSalt(salt);
        String b = member.getMobile().substring(member.getMobile().length() - 7, member.getMobile().length());
        member.setUserPwd(PasswordUtil.encrypt(member.getUserName(), b, salt));
        member.setLockVersion(1);
        member.setStatus(0);
        //设置分站
        String siteId = mkSiteBasicService.getSurroundingSiteId(member.getRegistLat(), member.getRegistLng()).getSiteId();
        log.info("-----设置分站id:" + siteId);
        member.setSiteId(siteId);
        if (super.baseMapper.insert(member) > 0) {
            String appSign = JwtUtil.appSign(member.getId());
            return Result.OK(new MemberLoginSuccessVO(appSign, member));
        } else {
            return Result.error("同步用户失败");
        }
    }

    @Override
    public IPage<Member> queryMemberPage(Page<Member> page, Member member) {
        this.handleMemberByUserType(member, (LoginUser) SecurityUtils.getSubject().getPrincipal());
        return super.baseMapper.queryMemberPage(page, member);
    }

    @Override
    public MemberVO queryMemberOneById(String id) {
        MemberVO memberVO = super.baseMapper.selectOneById(id);
        if (memberVO == null)
            throw new JeecgBootException("未找到相应会员信息, id-> " + id);
        return memberVO;
    }

    @Override
    public String addMember(Member member) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        this.handleMemberByUserType(member, loginUser);
        member.setCreateTime(new Date());
        member.setCreateBy(loginUser.getUsername());
        member.setDelFlag(CommonConstant.DEL_FLAG_0);
        member.setLockVersion(1);
        member.setStatus(0);

        super.baseMapper.insert(member);
        if (member.getId() == null)
            throw new JeecgBootException("新增会员信息失败");
        return member.getId();
    }

    /**
     * 根据用户类型处理信息发布实体数据
     *
     * @param member    信息发布实体
     * @param loginUser 当前登录用户
     */
    private void handleMemberByUserType(Member member, LoginUser loginUser) {
        // 根据用户类型判断
        if (MarketConstant.USER_TYPE_SITE.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getSiteId()))
                throw new JeecgBootException("用户暂未绑定分站, realName-> " + loginUser.getRealname());
            // 分站类型默认 查询该分站下的数据/插入分站
            member.setSiteId(loginUser.getSiteId());
        }
    }

    @Override
    public int updateMember(Member member) {
        member.setUpdateTime(new Date());
        member.setUpdateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());
        member.setDelFlag(null);

        int updateRecordCount = super.baseMapper.updateById(member);
        if (updateRecordCount == 0)
            throw new JeecgBootException("更新会员信息失败, id-> " + member.getId());
        return updateRecordCount;
    }

    @Override
    public int deleteMember(String id) {
        int deleteRecordCount = super.baseMapper.deleteById(id);
        if (deleteRecordCount == 0)
            throw new JeecgBootException("删除会员信息失败, id-> " + id);
        return deleteRecordCount;
    }

    @Override
    public int deleteBatchMember(List<String> ids) {
        int deleteRecordCount = super.baseMapper.deleteBatchIds(ids);
        if (deleteRecordCount < ids.size())
            throw new JeecgBootException(
                    String.format("批量删除会员信息失败, deleteRecordCount-> %s, ids.size()-> %s, ids-> %s",
                            deleteRecordCount, ids.size(), ids));
        return deleteRecordCount;
    }

    @Override
    public int memberStatusChange(String id) {
        int statusChangeRecordCount = super.baseMapper.update(null, Wrappers.<Member>lambdaUpdate()
                .setSql("status = !status")
                .eq(Member::getId, id));
        if (statusChangeRecordCount == 0)
            throw new JeecgBootException("会员信息状态变更失败, id-> " + id);
        return statusChangeRecordCount;
    }
}
